<template>
	<view class="container">
		<view class="head">
			<view class="top">
				<view class="left">
					数据中心
				</view>
				<view class="right">
					<image class="icon" src="/static/img/common/search2.png" @click="headBtnClick('search')"></image>
					<image class="icon" src="/static/img/common/share.png" @click="exportHanle" ></image>
				</view>
			</view>
			<!-- 出料收料选择框 -->
			<ButtonBox class="button-box" :btnArr="materialArr" @btnClick="changeMaterialStatus"></ButtonBox>
			<!-- 出料收料总计数量 -->
			<view class="material-items" v-if="nowMaterialStatus=='收料'">
				<view class="item-box">
					<view class="item top">
						<view class="left">
							<view class="title">
								累计收料方量
							</view>
							<view class="num">
								{{statisticalInfo.totalVolume}}
							</view>
						</view>
						<view class="right">
							<image class="icon" src="/static/img/consumption/discharging-square.png"></image>
						</view>
					</view>
					<view class="item bottom">
						<view class="left">
							<view class="title">
								累计收料趟次
							</view>
							<view class="num">
								{{statisticalInfo.total}}
							</view>
						</view>
						<view class="right">
							<image class="icon" src="/static/img/consumption/discharging-count.png"></image>
						</view>
					</view>
				</view>
				<view class="item-box item-box2">
					<view class="item top">
						<view class="left">
							<view class="title">
								累计内场收料
							</view>
							<view class="num">
								{{statisticalInfo.inVolume}}
							</view>
						</view>
						<view class="right">
							<image class="icon" src="/static/img/consumption/receiving-count.png"></image>
						</view>
					</view>
					<view class="item bottom">
						<view class="left">
							<view class="title">
								累计外场出料
							</view>
							<view class="num">
								{{statisticalInfo.outVolume}}
							</view>
						</view>
						<view class="right">
							<image class="icon" src="/static/img/consumption/receiving-count2.png"></image>
						</view>
					</view>
				</view>
			</view>
			<view class="material-items" v-else>
				<view class="item-box">
					<view class="item top">
						<view class="left">
							<view class="title">
								累计出料方量
							</view>
							<view class="num">
								{{statisticalInfo.totalVolume}}
							</view>
						</view>
						<view class="right">
							<image class="icon" src="/static/img/consumption/discharging-square.png"></image>
						</view>
					</view>
					<view class="item bottom">
						<view class="left">
							<view class="title">
								累计出料趟次
							</view>
							<view class="num">
								{{statisticalInfo.total}}
							</view>
						</view>
						<view class="right">
							<image class="icon" src="/static/img/consumption/discharging-count.png"></image>
						</view>
					</view>
				</view>
				<view class="item-box item-box2">
					<view class="item top">
						<view class="left">
							<view class="title">
								累计已签收方量
							</view>
							<view class="num">
								{{statisticalInfo.outVolume}}
							</view>
						</view>
						<view class="right">
							<image class="icon" src="/static/img/consumption/receiving-square.png"></image>
						</view>
					</view>
					<view class="item bottom">
						<view class="left">
							<view class="title">
								累计内场出料
							</view>
							<view class="num">
								{{statisticalInfo.inVolume}}
							</view>
						</view>
						<view class="right">
							<image class="icon" src="/static/img/consumption/receiving-count.png"></image>
						</view>
					</view>
				</view>
			</view>
			<!-- 出料收料列表 -->
			<scroll-view scroll-y class="scroll-y" @scrolltolower="loadMore">
				<block v-if="nowMaterialStatus === '收料'">
					<ReceivingItem v-for="item in receivingList" isSigned @click="goToDetailPage(item.orderId)"
						:key="item.orderId" :sign-info="item" />
					<!-- isSigned -->
				</block>

				<block v-else>
					<DischargingItem v-for="item in dischargingList" @click="goToDetailPage(item.orderId)"
						:key="item.orderId" :sign-info="item" />
				</block>
				<up-empty mode="list" text='还没有数据' :show="!listLen" textSize='25' iconSize='25' width='200' height='200'
					icon="http://cdn.uviewui.com/uview/empty/list.png"></up-empty>
				<up-loadmore :status="loadStatus" v-show='listLen>10' loading-text="努力加载中" loadmore-text="轻轻上拉"
					nomore-text="实在没有了" />
			</scroll-view>

		</view>
		<messageTip ref="myMessage"></messageTip>
	</view>
</template>

<script setup lang="ts">
	import { computed, reactive, ref } from 'vue';
	import {
		onShow
	} from "@dcloudio/uni-app"
	import ButtonBox from '@/components/buttonBox/buttonBox.vue';
	import ReceivingItem from '@/components/consumption/receivingItem/receivingItem.vue';
	import DischargingItem from '@/components/consumption/dischargingItem/dischargingItem.vue';
	import * as dataCenterApi from '@/api/consumption/dataCenter.js'
	import { useUserStore, useConsumptionStore } from '@/stroes';
	// import { saveAs } from 'file-saver';
	import * as XLSX from 'xlsx'

	import http from '@/api/api.js';
	const myMessage = ref()
	const userStore = useUserStore()
	const consumptionStore = useConsumptionStore()


	const materialArr = ['收料', '出料']
	// 当前物料状态
	const nowMaterialStatus = ref('收料')
	// 修改物料状态
	const changeMaterialStatus = (btn : string) => {
		nowMaterialStatus.value = btn
		consumptionStore.searchInfo = {}
		getList(1)
	}
	// 头部按钮点击
	const headBtnClick = (type : string) => {
		if (type == 'search') {
			let type = nowMaterialStatus.value === '收料' ? '2' : '1'
			uni.navigateTo({
				url: '/pages/consumption/dataSearch/dataSearch?orderType=' + type
			})
		}
	}

	// 收料列表
	const receivingList = ref([])
	// 出料列表
	const dischargingList = ref([])
	// 列表的长度
	const listLen = computed(() => {
		return nowMaterialStatus.value === '出料' ? dischargingList.value.length : receivingList.value.length
	})
	// 统计信息
	const statisticalInfo = reactive({
		// 累计收料方量/累计出料方量
		totalVolume: 0,
		// 累计内场收料/累计内场出料
		inVolume: 0,
		// 累计外场收料/累计已签收方量
		outVolume: 0,
		// 总条数
		total: 0
	})
	// 分页信息
	const pageInfo = reactive({
		current: 1,
		size: 10,
	})
	// 获取出料--收料列表
	const getList = (type : Number) => {
		// console.log('搜索条件', consumptionStore.searchInfo);
		uni.showLoading({
			title: '数据加载中...'
		})
		let obj = {
			// 出料--收料
			orderType: '',
			// 消纳场id
			terminalId: consumptionStore.nowVenue?.id,
			// 运企名称
			transportCompanyName: '',
			// 起点项目名称
			startingPlace: '',
			// 终点项目名称
			terminusPlace: '',
			// 起点厂区 []String
			startingFieldArea: [],
			// 终点厂区 []String
			terminusFieldArea: [],
			// 签收状态[]String 已签收 未签收
			orderStatus: [],
			// 签收人员id []Number
			signId: [],
			// 出料人id []Number
			senderId: [],
			// 是否为内转车[]String 0-1
			internal: [],
			// 是否为名录车[]String
			directory: [],
			//开始时间
			startTime: '',
			//结束时间 
			endTime: '',
			...pageInfo,
			...consumptionStore.searchInfo
		}
		if (nowMaterialStatus.value === '出料') {
			obj.orderType = '2';
			obj.startingFieldArea = [userStore.fieldArea];
			obj.senderId = [userStore.accountInfo['user_id']];
		} else {
			obj.orderType = '1';
			obj.terminusFieldArea = [userStore.fieldArea];
			obj.signId = [userStore.accountInfo['user_id']];
		}
		if (obj.startTime !== '') {
			obj.startTime = obj.startTime + ' 00:00:00'
		}
		if (obj.endTime !== '') {
			obj.endTime = obj.endTime + ' 23:59:59'
		}
		console.log("dddddssssssssssddddddddg", obj)
		dataCenterApi.getList(obj).then(res => {
			if (res.data && res.data.code == 0) {
				// console.log('获取列表', res.data.data.data.records);
				if (obj.orderType === '2') {
					if (type === 1) {
						dischargingList.value = res.data.data.data.records || []
					} else {
						dischargingList.value.push(...res.data.data.data.records)
					}
				} else if (obj.orderType === '1') {
					if (type === 1) {
						receivingList.value = res.data.data.data.records || []
					} else {
						receivingList.value.push(...res.data.data.data.records)
					}
				}
				statisticalInfo.totalVolume = res.data.data.totalVolume
				statisticalInfo.inVolume = res.data.data.inVolume
				statisticalInfo.outVolume = res.data.data.outVolume
				statisticalInfo.total = res.data.data.data.total
			}
			uni.hideLoading()
		})
	}
	// 加载状态
	const loadStatus = ref('loadmore')
	// 加载更多
	const loadMore = () => {
		if (statisticalInfo.total == listLen.value) {
			loadStatus.value = 'nomoreText';
			myMessage.value.open('error', '已经到底了哦！')
			return
		}
		pageInfo.current = pageInfo.current + 1
		loadStatus.value = 'loadingText';
		getList(2)
	}
	// 去详情页面
	const goToDetailPage = (id : string) => {
		uni.navigateTo({
			url: '/pages/consumption/dataItemDetail/dataItemDetail?id=' + id
		})
		/* 	if (nowMaterialStatus.value === '出料') {
				uni.navigateTo({
					url: '/pages/consumption/dischargingItemConfirm/dischargingItemConfirm?id=' + id
				})
			} else {
				uni.navigateTo({
					url: '/pages/consumption/receivingItemConfirm2/receivingItemConfirm2?type=1&id=' + id
				})
			} */
	}
	onShow(() => {
		if (userStore.nowPageId === 1) {
			// console.log('开始搜索数据');
			getList(1)
		}
	})
	function exportToExcel(data, fileName) {
		// 创建工作簿
		const wb = XLSX.utils.book_new();

		// 将数据转换为工作表
		const ws = XLSX.utils.json_to_sheet(data);

		// 将工作表添加到工作簿
		XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

		// 生成Excel的配置项
		const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });

		// 创建二进制对象并创建url
		const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });
		const url = URL.createObjectURL(blob);

		// 使用file-saver保存文件
		// saveAs(blob, fileName + '.xlsx');

		// 通过创建的URL下载文件
		const a = document.createElement('a');
		if (typeof a.download === 'undefined') {
			window.location = url;
		} else {
			a.href = url;
			a.download = fileName + '.xlsx';
			document.body.appendChild(a);
			a.click();
			document.body.removeChild(a);
		}

		// 清除对象URL
		setTimeout(function () { URL.revokeObjectURL(url); }, 100);
	}

	// 转换字符串为ArrayBuffer
	function s2ab(s) {
		const buf = new ArrayBuffer(s.length);
		const view = new Uint8Array(buf);
		for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
		return buf;
	}
	// 导出
	function exportHanle() {
		console.log("导出")
		let obj = {
			// 出料--收料
			orderType: '',
			// 消纳场id
			terminalId: Number(consumptionStore.nowVenue?.id),
			// 运企名称
			transportCompanyName: '',
			// 起点项目名称
			startingPlace: '',
			// 终点项目名称
			terminusPlace: '',
			// 起点厂区 []String
			startingFieldArea: [],
			// 终点厂区 []String
			terminusFieldArea: [],
			// 签收状态[]String 已签收 未签收
			orderStatus: [],
			// 签收人员id []Number
			signId: [],
			// 出料人id []Number
			senderId: [],
			// 是否为内转车[]String 0-1
			internal: [],
			// 是否为名录车[]String
			directory: [],
			//开始时间
			startTime: '',
			//结束时间 
			endTime: '',
			...pageInfo,
			...consumptionStore.searchInfo
		}
		if (nowMaterialStatus.value === '出料') {
			obj.orderType = '2';
			obj.startingFieldArea = [userStore.fieldArea];
			obj.senderId = [userStore.accountInfo['user_id']];
		} else {
			obj.orderType = '1';
			obj.terminusFieldArea = [userStore.fieldArea];
			obj.signId = [userStore.accountInfo['user_id']];
		}
		if (obj.startTime !== '') {
			obj.startTime = obj.startTime + ' 00:00:00'
		}
		if (obj.endTime !== '') {
			obj.endTime = obj.endTime + ' 23:59:59'
		}

		uni.request({
			url: http.baseURL + 'internal/dataExport', //接口地址：前缀+方法中传入的地址
			method: 'GET',
			data: obj,
			header: {
				'Authorization': 'Bearer ' + userStore?.accountInfo?.access_token,
			},
			success: (res) => {
				console.log("导出res",res)
				const fileName = 'download.xlsx';
				const filePath =`${plus.io.convertLocalFileSystemURL('downloads')}/${fileName}`;
				console.log("导出filePath",filePath)
				plus.io.resolveLocalFileSystemURL('downloads',(entry)=>{
					console.log("导出downloads",entry)
					entry.getFile(fileName,{ create:true },(fileEntry)=>{
						fileEntry.createWriter((writer)=>{
							console.log("导出writer",writer)
							// writer.write(new Blob([res.data]));
						})
					})
				})
			},
		})
	}
	function arrayBufferToBlob(buffer) {
		return new Blob([buffer]);
	}
	function previewExcel(arrayBuffer) {
		// 将ArrayBuffer转换为Sheetjs支持的工作簿类型
		const workbook = XLSX.read(arrayBuffer, { type: 'buffer' });

		// 获取工作簿的第一个Sheet
		const sheetName = workbook.SheetNames[0];
		const sheet = workbook.Sheets[sheetName];

		// 将Sheet转换为JSON
		const jsonData = XLSX.utils.sheet_to_json(sheet);

		// 输出JSON数据，你可以在这里进行UI渲染等操作
		console.log(jsonData);
	}
</script>

<style scoped lang="scss">
	.container {
		.head {
			position: relative;
			padding: 108rpx 34rpx 0rpx;
			// height: 432rpx;
			background: url('@/static/img/consumption/data-head.png') no-repeat no-repeat top center/ 750rpx 432rpx;
			box-sizing: border-box;

			>.top {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 24rpx;
				color: #fff;
				font-size: 32rpx;

				.icon {
					margin-left: 36rpx;
					width: 36rpx;
					height: 36rpx;
				}
			}

			.button-box {
				margin-bottom: 20rpx;
			}

			.material-items {
				display: flex;
				justify-content: space-between;
				align-items: center;
				box-sizing: border-box;

				.item-box {
					// flex: 1;
					width: 332rpx;
					background: url('@/static/img/consumption/data-item.png') no-repeat no-repeat center/ 100% 100%;

					.item {
						display: flex;
						justify-content: space-between;
						align-items: center;
						padding: 0rpx 24rpx 0rpx 24rpx;
						height: 160rpx;
						font-size: 28rpx;

						.num {
							margin-top: 12rpx;
							font-size: 36rpx;
							font-weight: bold;
						}
					}

					.icon {
						width: 60rpx;
						height: 52rpx;
					}

					&.item-box2 {
						background: url('@/static/img/consumption/data-item2.png') no-repeat no-repeat center/ 100% 100%;

						.icon {
							width: 60rpx;
							height: 62rpx;
						}
					}
				}
			}
		}

		.scroll-y {
			// margin-top: 340rpx;
			// background-color: skyblue;
			height: 850rpx;
			overflow: hidden;
		}
	}
</style>